/*!
 * Copyright (c) 2023-present StarDreamNet
 */
(document.loader || (document.loader = [])).push(["sendpost", class {
    constructor() {
        this.editor = null;
    };
    initEditorMD() {
        const loop = setInterval(() => {
            this.resize();
        }, 100);

        this.editor = editormd("test-editor", {
            height: 500,
            path: "/static/editormd/lib/",
            htmlDecode: false,
            imageUpload: true,
            imageFormats: ["jpg", "jpeg", "gif", "png", "bmp", "webp"],
            imageUploadURL: "../../api/upload/",
            emoji: true,
            toc: true,
            tocm: true,
            taskList: true,
            codeFold: true,
            tex: true,
            flowChart: true,
            sequenceDiagram: true,
            searchReplace: true,
            saveHTMLToTextarea: true,
            toolbarIcons() {
                return editormd.toolbarModes.full.concat("|", "upload", "download", "|", "release")
            },
            toolbarIconsClass: {
                upload: "fa-upload",
                download: "fa-download",
                release: "fa-paper-plane"
            },
            toolbarHandlers: {
                upload() {
                    var input = document.createElement("input");
                    input.type = "file";
                    input.accept = ".md,.txt";
                    input.onchange = () => {
                        const [file] = input.files;
                        const reader = new FileReader();
                        reader.onload = () => {
                            const text = reader.result;

                            swal({
                                title: "选择导入方式",
                                buttons: {
                                    cancel: "取消",
                                    confirm: false,
                                    z0: {
                                        text: "追加到末尾",
                                        value: "0",
                                    },
                                    z1: {
                                        text: "粘贴到光标",
                                        value: "1",
                                    },
                                    z2: {
                                        text: "覆盖",
                                        value: "2",
                                    },
                                }
                            }).then(v => {
                                if (!v) return;
                                switch (v) {
                                    case "0":
                                        const markdown = this.getMarkdown();
                                        this.setMarkdown(markdown + text);
                                        break;
                                    case "1":
                                        this.insertValue(text);
                                        break;
                                    case "2":
                                        this.setMarkdown(text);
                                        break;
                                    default:
                                        break;
                                }
                            })
                        };
                        reader.readAsText(file);
                    }
                    input.click();
                },
                download() {
                    const markdown = this.getMarkdown();
                    var objurl = (URL || webkitURL || window).createObjectURL(new Blob([markdown]));

                    var a = document.createElement("a");
                    a.download = "下载.md";
                    a.href = objurl;

                    a.click();
                },
                release() {
                    const data = {
                        title: $('.app-post-input').val(),
                        markdown: btoa(
                            encodeURIComponent(this.getMarkdown()).replace(
                                /%([0-9A-F]{2})/g,
                                function (match, p1) {
                                    return String.fromCharCode('0x' + p1);
                                }
                            )
                        ),
                        partition_id: $('#partition').attr('value'),
                    };

                    fetch('/api/shequ/send_post/', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify(data)
                    }).then(response => response.json())
                        .then(result => {
                            if (result.code == 200) {
                                swal.skip({
                                    title: "发帖成功",
                                    to: "帖子页面",
                                    src: "/post/" + result.data
                                });
                            } else {
                                swal("发帖失败", result.msg, "error");
                            }
                        })
                        .catch(() => {
                            swal("发帖失败", "请稍后再试", "error");
                        })
                }
            },
            lang: {
                toolbar: {
                    upload: "导入 .md / .txt 文件",
                    download: "导出为 .md 文件",
                    release: "发布帖子"
                }
            },
            onload() {
                clearInterval(loop);
                this.resize();
                this.setToolbarAutoFixed(false);
                this.config("pageBreak", true);
                this.setMarkdown(localStorage.getItem("ducksite_sendpost_markdown") || "");
            },
            onchange() {
                const markdown = this.getMarkdown();
                localStorage.setItem("ducksite_sendpost_markdown", markdown);
            }
        });
    };
    initTitle() {
        const input = $('.app-post-input')
        const title = localStorage.getItem("ducksite_sendpost_title");

        if (title) input.val(title);

        input.on('change', () => {
            localStorage.setItem("ducksite_sendpost_title", input.val());
        });
    };
    init_(require) {
        this.resize = require("index").resize;
        this.initEditorMD();
        this.initTitle();
    }
}])